<template>
  <div class="order-manage-container">
    <el-card class="order-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="订单号/客户姓名/手机号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="摄影师">
            <el-select
              style="width: 120px"
              v-model="searchForm.photographerId"
              placeholder="选择摄影师"
              clearable
            >
              <el-option
                v-for="item in photographerOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select
              style="width: 100px"
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option label="待确认" value="1" />
              <el-option label="已确认" value="2" />
              <!-- <el-option label="拍摄中" value="shooting" /> -->
              <el-option label="后期处理中" value="3" />
              <el-option label="已完成" value="4" />
              <el-option label="已取消" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付状态">
            <el-select
              style="width: 100px"
              v-model="searchForm.paymentStatus"
              placeholder="选择状态"
              clearable
            >
              <el-option label="未支付" value="1" />
              <el-option label="部分支付" value="2" />
              <el-option label="已支付" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="拍摄日期">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 订单列表 -->
      <el-table v-loading="loading" :data="orderList" style="width: 100%" border>
        <el-table-column prop="order_number" label="订单号" width="180" />

        <el-table-column label="客户信息" min-width="180">
          <template #default="{ row }">
            <div class="customer-info">
              <div>{{ row.customer_name }}</div>
              <div class="phone">{{ row.customer_phone }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="摄影师" width="120">
          <template #default="{ row }">
            {{ row.photographer.nickname }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="拍摄类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getShootingTypeTagType(row.shootingType)">
              {{ getShootingTypeLabel(row.shootingType) }}
            </el-tag>
          </template>
        </el-table-column> -->

        <el-table-column prop="shooting_date" label="拍摄日期" width="180" />

        <el-table-column label="订单金额" width="200">
          <template #default="{ row }">
            <div class="amount-info">
              <div>总额：¥{{ row.amount }}</div>
              <div>已付：¥{{ row.paid_amount }}</div>
              <div>待付：¥{{ row.amount - row.paid_amount }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="订单状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusTagType(row.status)">
              {{ getOrderStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="支付状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusTagType(row.payment_status)">
              {{ getPaymentStatusLabel(row.payment_status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)"> 查看详情 </el-button>
            <!-- <el-button
              class="confirm-btn"
              v-if="row.status === 1 && userRole === 'user' && currentUserId === row.customer_id"
              type="success"
              link
              @click="handleConfirm(row)"
            >
              确认订单
            </el-button> -->
            <el-button
              class="cancel-btn"
              v-if="
                [1, 2].includes(row.status) &&
                userRole === 'user' &&
                currentUserId === row.customer_id
              "
              type="danger"
              link
              @click="handleCancel(row)"
            >
              取消订单
            </el-button>
            <el-button
              class="confirm-btn"
              v-if="row.status === 3 && userRole === 'user' && currentUserId === row.customer_id"
              type="success"
              link
              @click="handleComplete(row)"
            >
              完成订单
            </el-button>
            <el-button
              class="confirm-btn"
              v-if="
                row.status === 4 &&
                userRole === 'user' &&
                currentUserId === row.customer_id &&
                !row.is_review
              "
              type="success"
              link
              @click="handleReview(row)"
            >
              评价
            </el-button>
            <!-- <el-button
              class="confirm-btn"
              v-if="row.status === 2 && userRole != 'user' && row.payment_status === 1"
              type="success"
              link
              @click="handleDepositReceived(row)"
            >
              已收定金
            </el-button> -->
            <el-button
              class="confirm-btn"
              v-if="row.status === 2 && userRole != 'user' && row.payment_status === 2"
              type="success"
              link
              @click="handleFinishedReceived(row)"
            >
              已收尾款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="订单详情" width="700px">
        <div class="order-detail" v-if="currentOrder">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号">{{
              currentOrder.order_number
            }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{
              currentOrder.created_at
            }}</el-descriptions-item>
            <el-descriptions-item label="客户姓名">{{
              currentOrder.customer_name
            }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{
              currentOrder.customer_phone
            }}</el-descriptions-item>
            <el-descriptions-item label="摄影师">{{
              currentOrder.photographer.nickname
            }}</el-descriptions-item>
            <!-- <el-descriptions-item label="拍摄类型">
              {{ getShootingTypeLabel(currentOrder.shootingType) }}
            </el-descriptions-item> -->
            <el-descriptions-item label="拍摄日期">{{
              currentOrder.shooting_date
            }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getOrderStatusTagType(currentOrder.status)">
                {{ getOrderStatusLabel(currentOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="总金额">¥{{ currentOrder.amount }}</el-descriptions-item>
            <el-descriptions-item label="已付金额"
              >¥{{ currentOrder.paid_amount }}</el-descriptions-item
            >
            <el-descriptions-item label="支付状态">
              <el-tag :type="getPaymentStatusTagType(currentOrder.payment_status)">
                {{ getPaymentStatusLabel(currentOrder.payment_status) }}
              </el-tag>
            </el-descriptions-item>
            <!-- <el-descriptions-item label="支付时间">
              {{ currentOrder.payment_time || '-' }}
            </el-descriptions-item> -->
          </el-descriptions>

          <div class="remark" v-if="currentOrder.remark">
            <div class="remark-title">备注信息</div>
            <div class="remark-content">{{ currentOrder.remark }}</div>
          </div>
        </div>
      </el-dialog>

      <!-- 评价对话框 -->
      <ReviewDialog
        v-model:visible="reviewDialogVisible"
        :order-id="currentOrderId"
        @success="handleReviewSuccess"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Order, OrderQuery } from '@/types/order'
import {
  cancelOrder,
  completeOrder,
  confirmDeposit,
  confirmFinalPayment,
  confirmOrder,
  getOrders,
} from '@/api/order'
import { getUserInfo } from '@/api/user'
import { useUserStore } from '@/stores/user'
import ReviewDialog from '@/components/ReviewDialog.vue'
import { useRouter } from 'vue-router'
import { getPhotographersList } from '@/api/photographer' // 导入获取摄影师列表的API
import type { Photographer } from '@/types/photographer' // 导入摄影师类型

const router = useRouter()

// 添加用户信息相关的变量
const userStore = useUserStore()
const userRole = computed(() => userStore.userRole)
const currentUserId = computed(() => userStore.userDetail?.id)

// 摄影师选项
const photographerOptions = ref<Photographer[]>([])

// 搜索表单
const searchForm = reactive<OrderQuery>({
  keyword: '',
  status: undefined,
  paymentStatus: undefined,
  startTime: undefined,
  endTime: undefined,
  photographerId: undefined, // 添加摄影师ID字段
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref<Order | null>(null)

// 订单列表数据
const orderList = ref<Order[]>([])

// 评价相关
const reviewDialogVisible = ref(false)
const currentOrderId = ref(0)

// 获取订单状态标签类型
const getOrderStatusTagType = (status: number) => {
  const types: Record<number, string> = {
    1: 'warning',
    2: 'primary',
    // 3: 'success',
    3: 'success',
    4: 'info',
    5: 'danger',
  }
  return types[status]
}

// 获取订单状态标签文本
const getOrderStatusLabel = (status: number) => {
  const labels: Record<number, string> = {
    1: '待确认',
    2: '已确认',
    // 3: '拍摄中',
    3: '后期处理中',
    4: '已完成',
    5: '已取消',
  }
  return labels[status]
}

// 获取支付状态标签类型
const getPaymentStatusTagType = (status: number) => {
  const types: Record<number, string> = {
    1: 'danger',
    2: 'warning',
    3: 'success',
  }
  return types[status]
}

// 获取支付状态标签文本
const getPaymentStatusLabel = (status: number) => {
  const labels: Record<number, string> = {
    1: '未支付',
    2: '部分支付',
    3: '已支付',
  }
  return labels[status]
}

// 处理日期范围变化
const handleDateRangeChange = (val: [string, string] | null) => {
  if (val) {
    searchForm.startTime = val[0]
    searchForm.endTime = val[1]
  } else {
    searchForm.startTime = undefined
    searchForm.endTime = undefined
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = undefined
  searchForm.paymentStatus = undefined
  searchForm.startTime = undefined
  searchForm.endTime = undefined
  dateRange.value = null
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 查看详情
const handleViewDetail = (row: Order) => {
  router.push(`/order/${row.id}`)
}

// 确认订单
const handleConfirm = async (row: Order) => {
  try {
    await ElMessageBox.confirm(
      '确认订单信息无误，客服将会在两个工作日内联系您选婚纱礼服并收取定金，定金支付后不退哦～',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
    // await confirmOrder(row.id)
    ElMessage.success('订单已确认')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleComplete = async (row: Order) => {
  try {
    await ElMessageBox.confirm('确定要完成这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await completeOrder(row.id)
    ElMessage.success('订单已完成')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleReview = (row: Order) => {
  currentOrderId.value = row.id
  reviewDialogVisible.value = true
}

const handleReviewSuccess = () => {
  fetchData()
}

const handleDepositReceived = async (row: Order) => {
  // 已收定金，修改支付状态
  try {
    await ElMessageBox.confirm('确定已经收到定金？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await confirmDeposit(row.id)
    ElMessage.success('已收定金')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleFinishedReceived = async (row: Order) => {
  // 已收尾款，修改订单状态
  try {
    await ElMessageBox.confirm('确定已经收到尾款？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await confirmFinalPayment(row.id)
    ElMessage.success('已收尾款')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 取消订单
const handleCancel = async (row: Order) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await cancelOrder(row.id)
    ElMessage.success('订单已取消')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

/**
 * 获取摄影师列表用于筛选
 * 该函数从服务器获取所有摄影师信息，用于订单筛选
 */
const fetchPhotographers = async () => {
  try {
    const { data } = await getPhotographersList({
      pageSize: 100, // 获取足够多的摄影师数据用于筛选
    })
    photographerOptions.value = data.data.items
  } catch (error) {
    ElMessage.error('获取摄影师列表失败')
  }
}

// MARK: 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getOrders({
      keyword: searchForm.keyword,
      status: searchForm.status ? Number(searchForm.status) : undefined,
      payment_status: searchForm.paymentStatus ? Number(searchForm.paymentStatus) : undefined,
      start_date: searchForm.startTime,
      end_date: searchForm.endTime,
      photographer_id: searchForm.photographerId, // 添加摄影师ID参数
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    orderList.value = data.data.items
    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
    return []
  } finally {
    loading.value = false
  }
}

const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    userStore.updateUserDetails(data.data)
    fetchData()
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

onMounted(() => {
  fetchUserInfo()
  fetchPhotographers() // 在组件挂载时获取摄影师列表
})
</script>

<style scoped>
.order-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.order-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.customer-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.phone {
  color: #666;
  font-size: 13px;
}

.amount-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  padding: 20px;
}

.remark {
  margin-top: 20px;
}

.remark-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.remark-content {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  color: #666;
}

.detail-btn {
  margin-right: 12px;
}
.confirm-btn {
  margin-left: 0px;
  margin-right: 12px;
}
.cancel-btn {
  margin-left: 0px;
}
</style>
